/**
 * Created by kevin on 2017/01/08.
 *
 * LotteryCircle
 */


var eosi = window.eosi || {};
this.eosi.website = this.eosi.website || {};

(function (window) {
    // the application


    function LotteryCircle(config,src) {

        this.Container_constructor();
        this.config = config;
        this.src=src;
        //console.log(this.config)
        this.init();
        //console.log(this.father.targetWidth);

    }

    var p = createjs.extend(LotteryCircle, createjs.Container);
    p.className = "LotteryCircle";
    p.config;
    p.resIsLoaded = false;
    p.resItems=[];
    p.loader;
    p.isDraw = false;
    p.lotteryConfig;
    p.circleDiameter;
    p.fatherBounds;
    p.circleHolder;
    p.initSpeed = 0;
    p.fastSpeed = 90;
    p.speed = 0;
    p.isLotterying = false;
    p.selectedId = -1;
    p.isStarted = false;
    p.src=null;
    // public methods:
    p.init = function () {

        this.loadRes();

        //this.on("removed",this.distoryPage,this);

    }



    /*
     * 加载资源
     * */
    p.loadRes = function(){
        this.resItems = [];
        this.loader = new createjs.LoadQueue(true);
        this.loader.on("complete", this.loadComplete, this);
        this.loader.on("fileload", this.onLoaded, this);
        this.loader.on("progress", this.onProgress, this);
        //console.log(this.config.src);

        //return
        this.loader.loadManifest({src: this.src+"?v="+version, callback: this.config.r_type.manifestCallback, type: "manifest"}, true);

    }
    /*
     * 资源加载
     * */
    p.onLoaded = function (evt){
        var item = evt.item;

        this.resItems.push(item);
        //console.log(this.resItems)
        //console.log(item)
        if(item.type == "manifest"){

            this.lotteryConfig = evt.result.lottery;
            console.log(this.lotteryConfig)
            //console.log(item.lottery);
        }

    }
    p.onProgress = function(evt){
        //console.log(evt);

        // if(LAND_PAGE){
        //     onProgress(evt);
        // }else{
        //     onProgress(evt,CORE_RES_SIZE_PER,1-CORE_RES_SIZE_PER);
        // }

    }
    /*
     * 资源加载完毕
     * */
    p.loadComplete = function (evt){
        //return;
        if(LAND_PAGE==null){
            LAND_PAGE = this;
        }
        this.resIsLoaded = true;
        this.config.resIsLoaded = this.resIsLoaded;
        //console.log(cur_page,this.name)
        //this.drawPage();

        //if(this.lotteryConfig.gifts.length in (4,6,9))
        this.drawLottery();

        //return;
        this.parent.setScale(this,this.resIndex);
        this.parent.setPos(this,this.resIndex);
        //animation
        this.parent.setAnimation(this,this.resIndex);

        onComplete(evt);
        //contentLayer.preload(this.pageIndex);

    }

    p.drawLottery = function(){

        this.fatherBounds = this.parent.getBounds();
        if(MY_SCREEN_ORIENTION == SCREEN_ORIENTION_V){
            this.circleDiameter = this.lotteryConfig.diameter*this.fatherBounds.width;
        }else{
            this.circleDiameter = this.lotteryConfig.diameter*this.fatherBounds.height;
        }
        this.setBounds(this.fatherBounds.x,this.fatherBounds.y,this.fatherBounds.width,this.fatherBounds.height);
        var pic = this.loader.getResult("lottery_circle_bg")
        var bg = new createjs.Bitmap(pic);
        //bg.regX = -pic.width*.5;
        //bg.regY = -pic.height*.5;
        this.addChild(bg);
        bg.name = "lottery_circle_bg";
        //console.log(this.parent);
        //console.log(this.parent.getBounds());

        this.circleHolder = new createjs.Container();

        var angle = Math.ceil(360 / this.lotteryConfig.gifts.length);
        //校准指标位置在第一块扇形的当中
        this.circleHolder.oriRotaion = this.lotteryConfig.starAngle-angle*.5;
        this.circleHolder.rotation = this.circleHolder.oriRotaion;
        //console.log(angle)
        for(var i=0;i<this.lotteryConfig.gifts.length;i++){
            var shanxingShape = new createjs.Shape();
            //x  y  半径  开始的角度  结束的角度  逆时针方向的
            //mc,x,y,r,angle,startFrom,color
            //console.log(i%this.lotteryConfig.giftColor.length)
            var c = this.lotteryConfig.giftColor[i%this.lotteryConfig.giftColor.length];

            this.drawSector(shanxingShape,0,0,this.circleDiameter *.5,angle,i*angle,c);
            this.circleHolder.addChild(shanxingShape);
            /*var giftPic = this.loader.getResult(this.lotteryConfig.gifts[i].pic_id);
            var gift = new createjs.Bitmap(giftPic);
            gift.regX = giftPic.width*.5;
            gift.regY = giftPic.height*.5;
            gift.name = this.lotteryConfig.gifts[i].pic_id;

            //console.log(this.circleHolder.getBounds());
            //gift.rotation = 90 + i*angle - this.circleHolder.rotation;
            gift.y=Math.sin(angle*i)*this.circleDiameter *.5*.7;
            gift.x=Math.cos(angle*i)*this.circleDiameter *.5*.7;
            //gift.scaleX = gift.scaleY = this.lotteryConfig
            this.circleHolder.addChild(gift);*/
            //console.log(gift.rotation)
        }
        for(var i=0;i<this.lotteryConfig.gifts.length;i++){
            var giftPic = this.loader.getResult(this.lotteryConfig.gifts[i].pic_id);
            var gift = new createjs.Bitmap(giftPic);
            gift.regX = giftPic.width*.5;
            gift.regY = giftPic.height*.5;
            gift.name = this.lotteryConfig.gifts[i].pic_id;
            //console.log(Math.sin(angle*i),Math.cos(angle*i))
            gift.y=Math.sin((angle*i+this.lotteryConfig.starAngle-this.circleHolder.oriRotaion)*Math.PI/180)*this.circleDiameter *.5*this.lotteryConfig.gifts[i].pos;
            gift.x=Math.cos((angle*i+this.lotteryConfig.starAngle-this.circleHolder.oriRotaion)*Math.PI/180)*this.circleDiameter *.5*this.lotteryConfig.gifts[i].pos;
            gift.rotation = -this.circleHolder.oriRotaion + i*angle+this.lotteryConfig.starAngle + 90;
            this.circleHolder.addChild(gift);
        }



        //console.log(this.circleHolder.rotation);
        this.addChild(this.circleHolder);

        //this.setAll(1);

        //console.log(this.getBounds());
        this.circleHolder.x = this.fatherBounds.width * this.lotteryConfig.pos.x;
        this.circleHolder.y = this.fatherBounds.height * this.lotteryConfig.pos.y;
        this.circleHolder.cache(-this.circleDiameter *.5, -this.circleDiameter *.5, this.circleDiameter, this.circleDiameter);

        //console.log(this.loader.getResult("lottery_circle_bg"))
        var lotteryStartBnPic = this.loader.getResult("lottery_start_bn");
        var lotteryStartBnBitmap = new createjs.Bitmap(lotteryStartBnPic);
        var lotteryStartBn = new eosi.website.BaseButton(lotteryStartBnBitmap);
        lotteryStartBn.regX = lotteryStartBnPic.width*.5;
        lotteryStartBn.regY = lotteryStartBnPic.height*.5;
        //console.log(lotteryStartBn);
        //lotteryStartBn.alpha =.5;
        lotteryStartBn.x=this.circleHolder.x;
        lotteryStartBn.y=this.circleHolder.y;

        //lotteryStartBn.addChild(lotteryStartBnBitmap);
        this.addChild(lotteryStartBn);
        lotteryStartBn.name = "lottery_start_bn";
        //lotteryStartBn.on("click",this.onClick,this);

        var lotteryZhizhenPic = this.loader.getResult("lottery_zhizhen");
        var lotteryZhizhenBitmap = new createjs.Bitmap(lotteryZhizhenPic);
        var lotteryZhizhen = new eosi.website.BaseButton(lotteryZhizhenBitmap);

        lotteryZhizhen.regX = lotteryZhizhenPic.width*.5;
        //lotteryZhizhen.regY = lotteryZhizhenPic.height*.5;
        switch (this.lotteryConfig.starAngle){
            case 270:
                lotteryZhizhen.x=this.circleHolder.x;
                lotteryZhizhen.y=this.circleHolder.y - this.circleDiameter *.5;
                break;
            case 0:
                lotteryZhizhen.x=this.circleHolder.x + this.circleDiameter *.5;
                lotteryZhizhen.y=this.circleHolder.y;
                lotteryZhizhen.rotation = 90;
                break;
            case 90:
                lotteryZhizhen.x=this.circleHolder.x ;
                lotteryZhizhen.y=this.circleHolder.y+ this.circleDiameter *.5;
                lotteryZhizhen.rotation = 180;
                break;
            case 180:
                lotteryZhizhen.x=this.circleHolder.x - this.circleDiameter *.5;
                lotteryZhizhen.y=this.circleHolder.y;
                lotteryZhizhen.rotation = 270;
                break;
            default :
                break;
                lotteryZhizhen.x=this.circleHolder.x;
                lotteryZhizhen.y=this.circleHolder.y - this.circleDiameter *.5;
        }

        //lotteryZhizhen.addChild(lotteryZhizhenBitmap);
        this.addChild(lotteryZhizhen);
        lotteryStartBn.name = "lottery_start_bn";

        this.setAll(0);


    }
    /*
    * 设置
    * */
    p.setAll = function(type){
        if(type == 0){//装饰元素
            for(var i=0;i<this.resItems.length;i++){
                var item = this.getChildByName(this.resItems[i].id);
                if(item){
                    this.setScale(item,this.resItems[i]);
                    this.setPos(item,this.resItems[i]);
                    this.setAnimation(item,this.resItems[i]);
                    this.setAction(item,this.resItems[i]);
                }

            }
        }else{//转盘内元素
            for(var i=0;i<this.lotteryConfig.gifts.length;i++){
                var item = this.circleHolder.getChildByName(this.lotteryConfig.gifts[i].pic_id);
                var config;
                for(var j=0;j<this.resItems.length;j++){
                    if(this.resItems[j].id == this.lotteryConfig.gifts[i].pic_id){
                        config = this.resItems[j];
                        //console.log(config);
                        break;

                    }
                }
                if(item){
                    this.setScale(item,config);
                    //this.setPos(item,config);
                    //this.setAnimation(item,config);
                    //this.setAction(item,config);
                }

            }
        }


    }
    /*
    * 绘制扇形
    * */
    p.drawSector = function (mc,x,y,r,angle,startFrom,color) {
        mc.graphics.clear();
        mc.graphics.beginFill(color);
        mc.graphics.moveTo(x, y);
        angle = (Math.abs(angle) > 360) ? 360 : angle;
        //为了使方法方便使用，这里的起始角度和扇形弧度都用角度表示，由于三角函数用的弧度制，这里先转换为弧度。
        startFrom = startFrom * Math.PI / 180;
        var x1=x+r * Math.cos(startFrom);
        var y1=y+r * Math.sin(startFrom);
        var endAngle=startFrom+angle*Math.PI/180;
        mc.graphics.lineTo(x1,y1);
        mc.graphics.arc(x,y,r,startFrom,endAngle,false);
        if (angle != 360){
            mc.graphics.lineTo(x, y);
        }
        mc.graphics.endFill();
    }





    /*
     * 设置scale
     * */
    p.setScale = function(item,config){
        var pic = item;
        // this.loader.getResult(this.resItems[i].id);
        switch (config.prop.fit){
            case "fit_all"://强制全屏
                //item.setTransform(0,0,targetWidth/pic.getBounds().width,targetHeight/pic.getBounds().height);
                item.scaleX= this.fatherBounds.width/pic.getBounds().width
                item.scaleY = this.fatherBounds.height/pic.getBounds().height
                //console.log(item.scaleX)
                break;
            case "fit_screen"://根据屏幕比例适配，不变性(相对于屏幕的比例)
                item.regX = pic.getBounds().width*.5;
                item.regY = pic.getBounds().height*.5;
                var ratio = config.prop.scale*this.fatherBounds.width/pic.getBounds().width;
                //item.setTransform(0,0,ratio,ratio);
                item.scaleX=item.scaleY= ratio;

                if(item.oriScale){
                    item.oriScale = ratio
                }
                break;

            default :
                break;
        }
    }

    /*
     * 设置位置
     * */
    p.setPos = function(item,config){
        if(config.pos.type == "abs"){//绝对位置
            switch (config.prop.align){
                case "TL":
                    item.x = 0;
                    item.y = 0;
                    break;
                case "TR":
                    item.x = this.fatherBounds.width;
                    item.y = 0;
                    break;
                case "TM":
                    item.x = this.fatherBounds.width*0.5;
                    item.y = 0;
                    break;
                case "BL":
                    item.x = 0;
                    item.y = this.fatherBounds.height;
                    break;
                case "BR":
                    item.x = this.fatherBounds.width;
                    item.y = this.fatherBounds.height;
                    break;
                case "BM":
                    item.x = this.fatherBounds.width*.5;
                    item.y = this.fatherBounds.height;
                    break;
                case "MM":
                    item.x = this.fatherBounds.width*.5;
                    item.y = this.fatherBounds.height*.5;
                    break;
            }
        }else if(config.pos.type == "rel"){//相对位置
            var father = this.getChildByName(config.pos.father);
            //console.log(father)
            if(father){
                item.x = father.x;
                item.y = father.y;
                //如果父亲也有动画，使用目标值作为参数的zhi
                if(father.proObj!=undefined){
                    //console.log(father.proObj)
                    if(father.proObj.y !=undefined){
                        item.y = father.proObj.y;
                    }
                    if(father.proObj.x !=undefined){
                        item.y = father.proObj.x;
                    }

                }

            }

        }

        item.x+=config.prop.offset.x * this.fatherBounds.width;
        item.y+=config.prop.offset.y * this.fatherBounds.height;
    }

    /*
     * 设置action
     * */
    p.setAction = function(item,config){
        var action = config.action
        if( action != "none"){
            var hit = new createjs.Shape();
            hit.graphics.beginFill("#000").drawRect(0,0,item.getBounds().width,item.getBounds().height);  // opaque black 50x50 square
            item.hitArea = hit;
            item.on("click",this.onClickItem,this);
            switch (action.type){
                case "popup"://弹窗s
                    item.group_id = action.group_id;
                    break;
                case "jumpto"://跳转
                    item.page = action.page;
                    break;
                case "func"://方法
                    //eval(action.funcName);
                    item.func = action.funcName;
                    break;
            }
            //window.location = "http://mywebsite.com/choose.php";

        }
    }

    /*
     * 点击事件
     * */
    p.onClickItem = function(evt){
        //console.log(evt.target)
        if(evt.target.page){
            contentLayer.jumpTo(evt.target.page);
        }
        if(evt.target.group_id){
            popupLayer.createPopup(evt.target.group_id);
        }

        if(evt.target.name = "lottery_start_bn"){
            evt.target.parent.start();
        }
        //console.log(evt.target.func)
        //this.setIconStatus(evt.target.name);
        //this.setIconStatus(evt.target);
    }
    p.start = function(evt){
        //console.log("ss")
        if(!this.isLotterying){
            this.selectedId = -1;
            this.isLotterying = !this.isLotterying;
            this.getResult();
            this.isStarted = true;
        }

    }

    /*
     * 设置animation
     * */
    p.setAnimation = function(item,config){
        var config = config.tween;
        //console.log(this.name);
        if(config){
            //console.log("aaaa")
            var tween = createjs.Tween.get(item,{loop:config.loop});
            if(config.wait){
                tween.wait(config.wait);
            }
            item.proObj = {};//记住对象的最终属性
            for(var key in config.prop){
                item.proObj[key] = item[key];//将目标参数记录在obj 中
                if(key!="y" && key!="x"){
                    item[key] = config.prop[key];//改变初始参数
                }else{
                    if(key=="y"){
                        item[key] = config.prop[key]*targetHeight;
                    }else{
                        item[key] = config.prop[key]*targetWidth;
                    }

                }

            }
            //console.log(item.proObj);
            tween.to(item.proObj, config.during,createjs.Ease[config.ease]);
            if(config.loop){
                tween.to(config.prop, config.during,createjs.Ease[config.ease]);
            }
            if(config.call){
                try
                {
                    tween.call(eval(config.call));
                }catch(e){
                    console.log(this.className+" no func '"+config.call+"'");
                    //alert("aa");

                }
            }

        }
    }


    p.tick = function(evt){
        if(!this.isStarted){
            return;
        }
        if(this.isLotterying){
            //console.log(this.speed);
            if(this.speed<this.fastSpeed){
                this.speed++;
            }else{

                if(this.selectedId != -1){
                    this.isLotterying = false;
                    console.log("选中",this.selectedId);

                    var stopAngle = this.getStopAngle();
                    //var targetRotation = this.circleHolder.rotation + (360 - this.circleHolder.rotation%360)+ 360*5 + stopAngle + this.lotteryConfig.starAngle;
                    var targetRotation =this.circleHolder.rotation + (360 - this.circleHolder.rotation%360) + (360 - (stopAngle + this.lotteryConfig.starAngle))  + 360*2;
                    console.log("to",targetRotation)
                    this.circleHolder.targetRotation = targetRotation;
                }

            }
            if(this.circleHolder){

                this.circleHolder.rotation+=this.speed;
                //console.log(this.circleHolder.rotation);
                //console.log(this.circleHolder.rotation)
            }
        }else{
            /*if(this.speed>this.initSpeed){
                this.speed-=this.speed/3;
            }
            if(this.circleHolder){
                if(this.circleHolder.rotation<this.circleHolder.targetRotation){
                    this.circleHolder.rotation+=this.speed;
                }else{
                    this.circleHolder.rotation = this.circleHolder.targetRotation;
                }


            }*/
            //var targetRotation = this.circleHolder.rotation + (360 - this.circleHolder.rotation%360)+ 360*2;
            var tween = createjs.Tween.get(this.circleHolder,{loop:false});
            tween.to({rotation:this.circleHolder.targetRotation}, 3000,createjs.Ease.quintOut);
            tween.call(this.finish);
            this.isStarted = false;
        }
        //console.log(evt);
    }
    p.finish = function(evt){
        //console.log(evt.target)
        var circleHolder = evt.target;
        var resetRotation = circleHolder.rotation%360;
        circleHolder.rotation = resetRotation;
        //console.log(circleHolder.parent.selectedId,circleHolder.parent.speed)
        circleHolder.parent.selectedId = -1;
        circleHolder.parent.speed = 0;
        console.log("finish");
    }

    /*
    * 命中结果
    * */
    p.getResult = function(){
        this.selectedId =this.lotteryConfig.gifts[Math.floor(Math.random()*this.lotteryConfig.gifts.length)].id;
        //return this.selectedId;
    }
    /*
    * 根据selectedId匹配转盘停止区域
    * return 停止角度，
    * */
    p.getStopAngle = function(){
        //var angle = 0;
        var index = this.lotteryConfig[Math.floor(Math.random()*this.lotteryConfig.defaultNoGift.length)];
        for(var i = 0 ;i<this.lotteryConfig.gifts.length ; i++){
            if(this.lotteryConfig.gifts[i].id == this.selectedId){
                index = i;
                break;
            }
        }
        var each = (360/this.lotteryConfig.gifts.length);
        var startAngle = each*(index);
        var endAngle = startAngle + each;
        var offset = 5;
        var angle = startAngle + offset + Math.random()*(each-offset*2);
        console.log(angle)
        return angle
    }






    // add MyApp to myNameSpace
    window.eosi.website.LotteryCircle = createjs.promote(LotteryCircle, "Container");
//}());
}(window));
